<?php
/**
 * 素材库
 */
namespace Api;
use Controller\Media as MediaC;
use Kuyuan\WqCore\api\Api;
use Kuyuan\WqCore\cache\Cache;
use Kuyuan\WqCore\util\Util;
use Kuyuan\WqCore\wx\Message;

class Media extends Api
{
    private $Media = null;

    // 需要远程服务器的文件集合
    private $_remote = array();

    public function __construct()
    {
        parent::__construct();
        $this->Media = new MediaC();
    }

    /**
     * 获取用户素材库列表
     */
    public function getList()
    {
        Util::appointGet();
        $_data = $this->Media->getList(0,$this->_gpc["type"],$this->_gpc["limit"]);
        if(count($_data) > 0){
            $_result = array("code"=>0,"data"=>$_data);
        } else {
            $_result = array("code"=>101);
        }
        Util::returns($_result);
    }

    /**
     * 上传
     */
    public function upload()
    {
        Util::appointPost();
        $_result = $this->Media->upload($this->_gpc["type"],$_FILES["file"]);
        // 模板消息通知管理员
        if (
            $_result["code"] == 0
            &&
            count($_result["remote"]) <= 0
        ) {
            if($this->testTplMessageNotice()) {
                $this->tplMessageNotice();
            }
        }
        Util::returns($_result);
    }

    /**
     * 检测是否模板消息通知，防止短时间内频繁模板消息通知
     */
    private function testTplMessageNotice()
    {
        global $_W;
        $_cache_name = KUYUAN_NAME.$_W["account"]["uniacid"]."media_await_check_tpl";
        if(Cache::name($_cache_name)) return false;
        Cache::name($_cache_name,KUYUAN_NAME,60);
        return true;
    }

    /**
     * 检测发送模板消息通知管理员审核素材
     * @param $_result
     */
    private function tplMessageNotice()
    {
        // 1、检测系统是否开启了审核功能
        $SettingMedia = $this->newController("SettingMedia");
        $_setting_media = $SettingMedia->find();
        if ($_setting_media["is_check"]) {
            // 3 、获取管理员列表
            $Manage = $this->newController("Manage");
            $_manage_list = $Manage->getList();
            if(count($_manage_list) > 0) {
                // 4.1、判断有没有设置模板消息id
                $SettingMessage = $this->newController("SettingMessage");
                $_setting_message = $SettingMessage->find();
                $_tpl_id = $_setting_message["await_check_tpl"];
                $Member = $this->newController("Member");
                $Setting = $this->newController("Setting");
                $_setting = $Setting->find();
                $_member = $Member->findNameHeader();
                load()->func('communication');
                foreach($_manage_list as $_v) {
                    $_tpl_result = Message::sendTpl(
                        $Member->uidToOpenid($_v["uid"]),
                        $_tpl_id,
                        array(
                            "first" => array(
                                "value" => $_setting["app_name"]."待审核通知"
                            ),
                            "keyword1" => array(
                                "value" => "用户上传素材"
                            ),
                            "keyword2" => array(
                                "value" => $_member["nickname"]
                            ),
                            "keyword3" => array(
                                "value" => date("Y-m-d H:i:s")
                            ),
                            "remark" => array(
                                "value" => "请登录后台处理素材审核"
                            )
                        )
                    );
                    if(!$_tpl_result) {
                        @ihttp_email(
                            $_v["email"],
                            $_setting["app_name"]."待审核通知",
                            array(
                                "<p>类型：用户上传素材</p><p>上传用户：".$_member["nickname"]."</p><p>上传时间：".date("Y-m-d H:i:s")."</p><p>请登录后台处理素材审核</p>"
                            )
                        );
                    }
                }
            }
        }
    }

    /**
     * 上传远程附件
     * @param array source 要上传的资源
     */
    public function remote()
    {
        Util::appointPost();
        $this->Media->remote($this->_gpc["source"]);
        if($this->_gpc["status"] != 2){
            if($this->testTplMessageNotice()) {
                $this->tplMessageNotice();
            }
        }
    }

    /**
     * 视频转码
     */
    public function transcoding()
    {
        Util::appointPost();
        $this->Media->transcoding($this->_gpc["media_id"],$this->_gpc["source"]);
        if($this->testTplMessageNotice()) {
            $this->tplMessageNotice();
        }
    }

    /**
     * 删除素材
     */
    public function delete()
    {
        Util::appointPost();
        $_uid = $this->Media->value($this->_gpc["media_id"],"uid");
        if($this->Media->delete($this->_gpc["media_id"])){
            // 删除素材，判断是否为后台审核，通知用户素材审核未通过
            if(isset($this->_gpc["source"]) && $this->_gpc["source"] == "manage_check") {
                $_params = array_merge(
                    $this->getMessageParams($_uid),
                    array(
                        "pass" => false,
                        "remark" => $this->_gpc["remark"]
                    )
                );
                $_tel_message_result = $this->sendTplMessage($_params);
                if(!$_tel_message_result) {
                    $this->sendSubscribeMessage($_params);
                }
            }
            $_result = array("code"=>0);
        } else {
            $_result = array("code"=>102);
        }
        Util::returns($_result);
    }

    /**
     * 修改素材状态
     */
    public function changeStatus()
    {
        Util::appointPost();
        try {
            if(!$this->Media->edit($this->_gpc["media_id"],array("status"=>$this->_gpc["status"]))){
                throw new \Exception("",101);
            }
            // 素材审核通过
            if($this->_gpc["status"] == 1 && isset($this->_gpc["source"]) && $this->_gpc["source"] == 'manage_check') {
                // 模板消息或者订阅消息通知用户
                // 整理发消息所需参数
                $_params = array_merge(
                    $this->getMessageParams(),
                    array(
                        "pass" => true,
                        "remark" => '无'
                    )
                );
                $_tel_message_result = $this->sendTplMessage($_params);
                if(!$_tel_message_result) {
                    $this->sendSubscribeMessage($_params);
                }
            }
            Util::returns(array("code"=>0));
        } catch (\Exception $e) {
            Util::returns(array("code"=>$e->getCode()));
        }
    }

    /**
     * 获取发送模板消息参数组
     * @param int $_uid 用户id
     * @return mixed
     */
    private function getMessageParams($_uid = 0)
    {
        $Member = $this->newController("Member");
        $_openid = $Member->uidToOpenid($_uid ? $_uid : $this->Media->value($this->_gpc["media_id"],"uid"));
        $SettingMessage = $this->newController("SettingMessage");
        $_setting_message = $SettingMessage->find();
        $Setting = $this->newController("Setting");
        $_setting = $Setting->find();
        return array(
            "openid" => $_openid,
            "templates" => $_setting_message,
            "app_name" => $_setting["app_name"],
        );
    }

    /**
     * 发送审核状态消息，模板消息
     * @param array $_params 参数数组
     * @params string $_openid 用户的openid
     * @params string $_template_id 模板消息id
     * @params string $_app_name 网站名字
     * @params bool $_pass 审核是否成功
     * @params string $_remark 审核失败后的备注消息
     * @return bool|mixed
     */
    private function sendTplMessage(Array $_params)
    {
        if(empty($_params["templates"]["result_check_tpl"])) return false;
        // 模板消息内容
        $_send_data = array(
            "first" => array(
                "value" => $_params["app_name"]."-素材审核结果"
            ),
            "keyword1" => array(
                "value" => "管理员"
            ),
            "keyword2" => array(
                "value" => $_params["pass"] ? "审核通过" : "审核未通过"
            ),
            "keyword3" => array(
                "value" => date("Y-m-d H:i:s")
            ),
            "remark" => array(
                "value" => $_params["remark"]
            )
        );
        return Message::sendTpl(
            $_params["openid"],
            $_params["templates"]["result_check_tpl"],
            $_send_data,
            murl('entry//mobile',array('m'=>'kuyuan_hb'),true,true)."#/member"
        );
    }

    /**
     * 发送审核状态消息，发送订阅消息
     * @param array $_params 参数
     * @params string $_openid 用户openid
     * @params string $_template_id 模板消息id
     * @params bool $_pass 是否通过审核
     * @params string $_remark 备注消息
     * @return mixed
     */
    private function sendSubscribeMessage(Array $_params)
    {
        if(empty($_params["templates"]["result_check_sub"])) return false;
        $_send_data = array(
            "thing10" => array(
                "value" => $_params["app_name"]."-素材审核结果"
            ),
            "phrase8" => array(
                "value" => $_params["pass"] ? "审核通过" : "审核未通过"
            ),
            "thing4" => array(
                "value" => $_params["remark"]
            ),
            "time9" => array(
                "value" => date("Y-m-d H:i:s")
            )
        );
        return Message::sendSubscribeMessage(
            $_params["openid"],
            $_params["templates"]["result_check_sub"],
            $_send_data,
            murl('entry//mobile',array('m'=>'kuyuan_hb'),true,true)."#/member"
        );
    }

    /**
     * 前端素材库通过id集合返回封面
     */
    public function formMediaThumb()
    {
        Util::appointGet();
        $_media_ids = $this->_gpc["media_id"];
        $_result = $this->Media->idsToThumb($_media_ids);
        Util::returns(array("code"=>0,"data"=>$_result));
    }

    /**
     * 获取用户素材库内存
     */
    public function getUserMemory()
    {
        Util::appointGet();
        $_data = $this->Media->getUserMemory();
        $_result = array("code"=>0,"data"=>$_data);
        Util::returns($_result);
    }

    /**
     * manage端获取需要审核的素材列表
     */
    public function getCheckList()
    {
        Util::appointGet();
        $_data = $this->Media->getCheckList($this->_gpc["limit"]);
        if($_data) {
            $Member = $this->newController("Member");
            foreach($_data as $_k=>$_v) {
                $_data[$_k]["user"] = $Member->findNameHeader($_v["uid"]);
            }
            $_result = array("code"=>0,"data"=>$_data);
        } else {
            $_result = array("code"=>101);
        }
        Util::returns($_result);
    }

    /**
     * manage端获取需要审核的素材列表总数
     */
    public function getCheckTotal()
    {
        Util::appointGet();
        Util::returns(array("code"=>0,"data"=>$this->Media->getCheckTotal()));
    }

}
